//
//  ImageScaleBrowser.m
//  ImageScaleBrowser
//
//  Created by Irewest on 14-9-12.
//  Copyright (c) 2014年 ci123.com. All rights reserved.
//

#import "ImageScaleBrowser.h"

#define IS_IOS7 [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0
#define STATUSBAR_HEIGHT    (IS_IOS7 ? 0:20)
#define ANIMATION_DURATION  .2f

@interface ImageScaleBrowser ()

@property (nonatomic,retain)id target;
@property (nonatomic,copy)NSString *urlString;
@property (nonatomic,retain)UIScrollView *scrollView;
@property (nonatomic,retain)UIImageView *originImageView;
@property (nonatomic,retain)UIImageView *showImageView;
@property (nonatomic,retain)UIActivityIndicatorView *incatorView;
@property (nonatomic,assign)CGRect originFrame;
@property (nonatomic,assign)BOOL isBig;

@end

@implementation ImageScaleBrowser

- (id)initWithTarget:(id)target {
    if ((self = [super init])) {
        _target = target;
        _isBig = NO;
        if (IS_IOS7) {
            [self setAutomaticallyAdjustsScrollViewInsets:NO];
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - STATUSBAR_HEIGHT)];
    [_scrollView setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_scrollView];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singleTap setNumberOfTapsRequired:1];
    [_scrollView addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    [_scrollView addGestureRecognizer:doubleTap];
    
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    float indicatorWidth = 37.0f;
    _incatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake((_scrollView.width - indicatorWidth) / 2, (_scrollView.height - indicatorWidth) / 2, indicatorWidth, indicatorWidth)];
    [_incatorView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [_incatorView startAnimating];
    [_scrollView addSubview:_incatorView];
    
    [self imageAppear];
}

- (void)imageAppear
{
    _showImageView = [[UIImageView alloc] initWithFrame:_originFrame];
    __weak typeof(self) weakSelf = self;
    [_showImageView setImageWithURL:[NSURL URLWithString:_urlString]
                   placeholderImage:_originImageView.image
                          completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
                              [weakSelf imageScaleDisplay:NO];
                              [weakSelf.incatorView stopAnimating];
                          }];
    [_showImageView setBackgroundColor:[UIColor clearColor]];
    [_showImageView setContentMode:UIViewContentModeScaleAspectFit];
    [_scrollView addSubview:_showImageView];
    
    [_scrollView bringSubviewToFront:_incatorView];
    
    [self imageScaleDisplay:NO];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private Methods

- (void)setOriginImageView:(UIImageView *)imageView withHighImageUrl:(NSString *)url
{
    _urlString = url;
    _originImageView = imageView;
    _originFrame = [_originImageView convertRect:_originImageView.bounds
                                          toView:[UIApplication sharedApplication].keyWindow];
}

- (void)handleSingleTap:(UITapGestureRecognizer *)singleTap
{
    [self hide];
}

- (void)handleDoubleTap:(UITapGestureRecognizer *)doubleTap
{
    if (_isBig) {
        [self imageScaleDisplay:NO];
    }else {
        [self imageScaleDisplay:YES];
    }
}

- (void)imageScaleDisplay:(BOOL)isBig
{
    CGSize size = CGSizeMake(_showImageView.image.size.width / 2, _showImageView.image.size.height / 2);
    float contentWidth = _scrollView.width;
    float contentHeight;
    CGSize fullSize = CGSizeMake(_scrollView.width, _scrollView.height);
    float newWidth = size.width;
    float newHeight = size.height;
    
    if (isBig) {
        fullSize = CGSizeMake(size.width, size.height);
        contentWidth = newWidth;
        _isBig = YES;
    }else {
        float scale = size.width / size.height;
        if (newWidth > fullSize.width) {
            newWidth = fullSize.width;
            newHeight = newWidth / scale;
        }
        _isBig = NO;
    }
    
    contentHeight = newHeight;
    
    float marginTop = (_scrollView.height - newHeight) / 2;
    float marginLeft = (_scrollView.width - newWidth) / 2;
    if (newWidth > _scrollView.width) {
        marginLeft = 0;
    }
    if (newHeight > _scrollView.height) {
        marginTop = 0;
    }
    
    [UIView animateWithDuration:ANIMATION_DURATION
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         [_showImageView setFrame:CGRectMake(marginLeft, marginTop, newWidth, newHeight)];
                     }
                     completion:^(BOOL finished){
                         [_scrollView setContentSize:CGSizeMake(contentWidth, contentHeight)];
                     }];
}

#pragma mark - Action

- (void)hide
{
    [UIView animateWithDuration:ANIMATION_DURATION
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^(void){
                         [_showImageView setFrame:CGRectMake(_originFrame.origin.x, _originFrame.origin.y - STATUSBAR_HEIGHT, _originFrame.size.width, _originFrame.size.height)];
                     }
                     completion:^(BOOL finished){
                         [self dismissViewControllerAnimated:YES completion:nil];
                     }];
}

- (void)show
{
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:self];
    [nc setNavigationBarHidden:YES];
    [nc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [_target presentViewController:nc animated:YES completion:nil];
}

@end
